//
//  Network.swift
//  
//
//  Created by 孙长坦 on 2022/4/18.
//

import Foundation
import Alamofire
import RxSwift
import LibBase

public class Network {
    
    static public let shared = Network()
    
    public private(set) lazy var reachabilityListener: BehaviorSubject<NetworkReachabilityManager.NetworkReachabilityStatus> = {
        reachabilityManager?.startListening(onUpdatePerforming: { [weak self] status in
            self?.reachabilityListener.onNext(status)
        })
        
        return BehaviorSubject(value: reachabilityManager?.status ?? .unknown)
    }()
    
    private lazy var reachabilityManager = {
        return NetworkReachabilityManager(host: dataSource?.reachabiltyHost() ?? "www.apple.com.cn")
    }()
    
    public weak var dataSource: NetworkDataSource?
    
    public var tokenType: String? {
        dataSource?.getTokenType(network: self)
    }
    
    public var token: String? {
        dataSource?.getToken(network: self)
    }
    
    public var appID: String? {
        dataSource?.getAppID(network: self)
    }
    
    public var serviceAddressRepository: DataRepository<ServiceAddressModel>?
    
    private init() {}
    
    public func initNetwork(serviceAddressRepository: DataRepository<ServiceAddressModel>?,
                            dataSource: NetworkDataSource?) {
        self.serviceAddressRepository = serviceAddressRepository
        self.dataSource = dataSource
        
        WebSocketService.shared.initWebSocket()
    }
}
